import React, { PureComponent } from 'react'
import { Table, notification, Button, Popconfirm, Alert, Popover, Divider, message } from 'antd'
import { connect } from 'dva'
import router from 'umi/router'
import Viewer from 'react-viewer'
import styles from './Index.less'
// import { getValue } from '@/utils/utils'
import PropModal from '../propCheck/PropModal'
import { getImgPrefix } from '@/utils/utils'

@connect(({ loading, propRepair }) => ({
  propRepair,
  loading: loading.models.propRepair,
}))
export default class List extends PureComponent {
  componentWillUnmount() {
    this.props.dispatch({
      type: 'propRepair/updateState',
      payload: {
        selectedRowKeys: [],
      },
    })
  }

  handleAdd = () => {
    // 清空currentItem
    this.props.dispatch({
      type: 'propRepair/updateState',
      payload: {
        currentItem: {},
      },
    })
    router.push('/property/repairupdate')
  }

  // 清除选择
  cleanSelectedKeys = () => {
    this.handleSelectRows([])
  }

  // 行选事件
  handleSelectRows = rows => {
    const { dispatch } = this.props
    dispatch({
      type: 'propRepair/updateState',
      payload: {
        selectedRowKeys: rows,
      },
    })
  }

  // 编辑
  handleEditClick = async record => {
    if (record.id) {
      try {
        await this.props.dispatch({
          type: 'propRepair/edit',
          payload: {
            id: record.id,
          },
        })

        router.push('/property/repairupdate')
      } catch (error) {
        console.log(error)
      }
    } else {
      notification.error('没有选择记录')
    }
  }

  handleShowView = async (record, e) => {
    e.preventDefault()
    try {
      await this.props.dispatch({
        type: 'propRepair/edit',
        payload: {
          id: record.id,
        },
      })

      const { imgList } = this.props.propRepair.currentItem

      if (imgList && imgList.length > 0) {
        this.props.dispatch({
          type: 'propRepair/updateState',
          payload: {
            showView: true,
          },
        })
      } else {
        message.info('暂无图片')
      }
    } catch (error) {
      console.log(error)
    }
  }

  handleShowProps = async (record, e) => {
    e.preventDefault()
    const { dispatch } = this.props
    await dispatch({
      type: 'propRepair/edit',
      payload: {
        id: record.id,
      },
    })

    dispatch({
      type: 'propRepair/updateState',
      payload: {
        showProps: true,
      },
    })
  }

  handleDelete = e => {
    e.preventDefault()
    const { selectedRowKeys } = this.props.propRepair
    const { dispatch } = this.props
    dispatch({
      type: 'propRepair/remove',
      payload: {
        ids: selectedRowKeys,
      },
    })
  }

  // 表格动作触发事件
  handleListChange = (pg, filtersArg, sorter) => {
    const { dispatch } = this.props
    const { formValues, pagination } = this.props.propRepair
    if (sorter.field && pagination.currentPage === pg.current) {
      return
    }

    const params = {
      ...formValues,
      current: pg.current,
    }

    dispatch({
      type: 'propRepair/fetchList',
      payload: params,
    })
  }

  render() {
    const { loading, dispatch } = this.props
    const {
      list,
      pagination,
      selectedRowKeys,
      showProps,
      currentItem: { items: PropsData, imgList },
      currentSteps,
      showView,
    } = this.props.propRepair

    const propImages =
      imgList && imgList.length > 0
        ? imgList.map(item => {
            const pathObj = JSON.parse(item.path)
            return {
              src: `${getImgPrefix()}${pathObj.sourceName}`,
            }
          })
        : [{ src: '' }]

    const propModalProps = {
      showModal: showProps,
      dataSource: PropsData,
      dataSteps: currentSteps,
      modalCloseCallback: () => {
        dispatch({
          type: 'propRepair/updateState',
          payload: {
            showProps: false,
            currentItem: {},
          },
        })
      },
    }

    const rowSelectionProps = {
      selectedRowKeys,
      getCheckboxProps: record => ({
        disabled: record.status !== '0001',
      }),
      onChange: selectedKeys => {
        this.handleSelectRows(selectedKeys)
      },
    }

    const columns = [
      {
        render: (t, r, i) => i + 1,
        width: 35,
      },
      {
        title: '报修单号',
        align: 'center',
        dataIndex: 'orderNo',
        width: 200,
        sorter: (a, b) => a.orderNo && a.orderNo.localeCompare(b.orderNo),
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: '报修单名称',
        align: 'center',
        sorter: (a, b) => a.repairName && a.repairName.localeCompare(b.repairName),
        dataIndex: 'repairName',
        width: 130,
      },
      {
        title: '报修类型',
        align: 'center',
        width: 80,
        dataIndex: 'repairTypeName',
      },
      {
        title: '报修人',
        align: 'center',
        width: 100,
        dataIndex: 'repairUserName',
      },
      {
        title: '报修日期',
        align: 'center',
        width: 100,
        dataIndex: 'gmtRepair',
      },
      {
        title: '状态',
        align: 'center',
        width: 80,
        render: (text, record) => {
          if (record.status === '0000') {
            return (
              <Popover
                content={
                  <div className={styles.popoverBox}>
                    <div>
                      <span>审批:</span>
                      {record.reasonUser || ''}
                    </div>
                    <div>
                      <span>日期:</span>
                      {record.reasonDate || ''}
                    </div>
                    <div>
                      <span>备注:</span>
                      {record.reason || ''}
                    </div>
                  </div>
                }
              >
                <a>{record.statusName}</a>
              </Popover>
            )
          }
          return record.statusName
        },
      },
      {
        title: '操作',
        align: 'center',
        width: 80,
        // fixed: 'right',
        render: (text, record) => {
          if (record.status === '0001') {
            return (
              <div>
                <a onClick={e => this.handleEditClick(record, e)}>修改</a>
                <Divider type="vertical" />
                <a onClick={e => this.handleShowView(record, e)}>查看图片</a>
              </div>
            )
          }
          return (
            <div>
              <a onClick={e => this.handleShowProps(record, e)}>查看资产</a>
              <Divider type="vertical" />
              <a onClick={e => this.handleShowView(record, e)}>查看图片</a>
            </div>
          )
        },
      },
    ]

    return (
      <div className={styles.standardTable}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            paddingTop: 15,
            paddingBottom: 15,
            backgroundColor: '#fff',
          }}
        >
          <div className={styles.tableTopbtns}>
            <Button icon="plus" type="primary" loading={loading} onClick={this.handleAdd}>
              新增报修单
            </Button>
            <Popconfirm
              title="确定要删除吗？"
              okText="确定"
              cancelText="取消"
              onConfirm={e => this.handleDelete(e)}
            >
              <Button type="danger" loading={loading}>
                删除
              </Button>
            </Popconfirm>
          </div>
        </div>
        <Alert
          style={{ marginBottom: 8 }}
          message={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
              <a style={{ marginLeft: 24 }} onClick={() => this.handleSelectRows([])}>
                清空选择
              </a>
            </div>
          }
          type="info"
          showIcon
        />
        <Table
          loading={loading}
          size="small"
          bordered
          dataSource={list}
          rowKey={record => record.id}
          pagination={pagination}
          columns={columns}
          onChange={this.handleListChange}
          rowSelection={rowSelectionProps}
          // scroll={{ x: 800 }}
        />
        <PropModal {...propModalProps}></PropModal>
        <Viewer
          visible={showView}
          onClose={() => {
            dispatch({ type: 'propRepair/updateState', payload: { showView: false } })
          }}
          images={propImages}
        />
      </div>
    )
  }
}
